package com.liu.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.liu.mapper.UserMapper;
import com.liu.Utils.ExcelListener;
import com.liu.Utils.JsonData;
import com.liu.pojo.User;
import com.liu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

        @Autowired
        private UserMapper userMapper;

        @Override
        public JsonData insert(MultipartFile file) {

            try {
                if (!StringUtils.isEmpty(file)){

                    InputStream inputStream = file.getInputStream();
                    ExcelListener listener = new ExcelListener();
                    EasyExcelFactory.read(inputStream, User.class,listener).headRowNumber(1).build().readAll();
                    List<Object> list = listener.getDatas();
                    if (ObjectUtils.isEmpty(list.get(0))) {
                        return JsonData.buildError("导入数据为空");
                    }
                    if (list.size()>0){
                        for (int i = 0; i < list.size(); i++) {

                            User user = (User)list.get(i);
                             userMapper.insertBy(user);

                        }

                    }

                }else {
                    JsonData.buildError("文件为空");
                }
            }catch (Exception e){
                e.printStackTrace();

            }

            return JsonData.buildSuccess("200");
        }
}
